/**
 * API服务模块
 */
import axios, { AxiosInstance, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import {
  User,
  UserProfile,
  UserLogin,
  UserRegister,
  UserUpdate,
  UserPasswordChange,
  UserPreferenceUpdate,
  Token,
  UserResponse,
  UserProfileResponse,
  TokenResponse,
  ApiResponse
} from '../types/user'
import type { Character, Novel, CharacterDetailResponse, NovelListResponse, NovelDetailResponse } from '../types/novel'

// API 基础配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000'
const API_VERSION = '/api/v1'

const api: AxiosInstance = axios.create({
  baseURL: `${API_BASE_URL}${API_VERSION}`,
  timeout: 60000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 可以在这里添加认证 token
    const token = localStorage.getItem('access_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data
  },
  (error) => {
    console.error('API Error:', error)
    return Promise.reject(error)
  }
)

// 用户认证API
export const authApi = {
  // 用户注册
  register: (data: UserRegister): Promise<UserResponse> => {
    return api.post('/auth/register', data)
  },

  // 用户登录
  login: (data: UserLogin): Promise<TokenResponse> => {
    return api.post('/auth/login', data)
  },

  // 刷新token
  refreshToken: (refreshToken: string): Promise<TokenResponse> => {
    return api.post('/auth/refresh', { refresh_token: refreshToken })
  },

  // 登出
  logout: (): Promise<ApiResponse> => {
    return api.post('/auth/logout')
  },

  // 忘记密码 - 通过邮箱和图形验证码重置密码
  forgotPassword: (data: { email: string; captcha: string; new_password: string }): Promise<ApiResponse> => {
    return api.post('/auth/forgot-password', data)
  },

  // 获取当前用户信息
  getCurrentUser: (): Promise<UserResponse> => {
    return api.get('/auth/me')
  }
}

// 用户资料API
export const userApi = {
  // 获取用户完整资料
  getProfile: (): Promise<UserProfileResponse> => {
    return api.get('/users/profile')
  },

  // 更新用户资料
  updateProfile: (data: UserUpdate): Promise<UserResponse> => {
    return api.put('/users/profile', data)
  },

  // 修改密码
  changePassword: (data: UserPasswordChange): Promise<ApiResponse> => {
    return api.post('/users/change-password', data)
  },

  // 上传头像
  uploadAvatar: (file: File): Promise<ApiResponse> => {
    const formData = new FormData()
    formData.append('file', file)
    return api.post('/users/upload-avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 获取用户偏好设置
  getPreferences: (): Promise<ApiResponse> => {
    return api.get('/users/preferences')
  },

  // 更新用户偏好设置
  updatePreferences: (data: UserPreferenceUpdate): Promise<ApiResponse> => {
    return api.put('/users/preferences', data)
  }
}

// 文件上传API
export const fileApi = {
  // 上传头像
  uploadAvatar: (file: File): Promise<ApiResponse> => {
    const formData = new FormData()
    formData.append('file', file)
    return api.post('/files/upload/avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 上传图片
  uploadImage: (file: File, imageType: string = 'general'): Promise<ApiResponse> => {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('image_type', imageType)
    return api.post('/files/upload/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 批量上传文件
  uploadBatchFiles: (files: File[], fileType: string = 'general'): Promise<ApiResponse> => {
    const formData = new FormData()
    files.forEach(file => {
      formData.append('files', file)
    })
    formData.append('file_type', fileType)
    return api.post('/files/upload/batch', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}

// 小说相关 API
export const novelApi = {
  // 获取小说列表
  async getNovelList(): Promise<Novel[]> {
    const response: NovelListResponse = await api.get('/novels/')
    if (response && response.data) {
      return response.data
    }
    return []
  },

  async getNovelDetail(novelId: number): Promise<Novel> {
    const response: NovelDetailResponse = await api.get(`/novels/${novelId}`)
    if (response && response.data) {
      return response.data
    }
    throw new Error('Failed to get novel detail')
  },

  // 获取角色详情
  async getCharacterDetail(novelId: number, characterId: number): Promise<Character> {
    const response: CharacterDetailResponse = await api.get(
      `/novels/${novelId}/characters/${characterId}`
    )
    if (response && response.data) {
      return response.data
    }
    throw new Error('Failed to get character detail')
  }
}

export default api 